package lucene.server.web.dao;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lucene.server.database.pool.PoolManager;
import lucene.server.database.pool.PooledConnection;
import lucene.server.web.model.ConnConfig;


import java.sql.SQLException;
import java.util.List;

@Slf4j
public class DynamicDataSource {



    public static void init() throws SQLException {
        //数据库连接初始化
        PoolManager.poolInit();
        List<ConnConfig> listAll =  Db.use().findAll(Entity.create("conn"),ConnConfig.class );
        listAll.forEach(connConfig -> {
            try {
                DynamicDataSource.createPool(connConfig);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @SneakyThrows
    public static ConnConfig getConnConfig(String connName)  {
        Entity entity =  Db.use().get(Entity.create("conn").set("connName", connName));
        if (entity == null){
            return null;
        }else {
            return entity.toBeanIgnoreCase(ConnConfig.class);
        }
    }
    @SneakyThrows
    public static PooledConnection createPool(ConnConfig connConfig) throws SQLException {
        PoolManager.createConnection(
                connConfig.getConnName(),
                connConfig.getConnUrl(),
                connConfig.getConnUser(),
                connConfig.getConnPassword(),
                connConfig.getConnDriver(),
                connConfig.getConnType()
        );
        return PoolManager.getConnection(connConfig.getConnName());
    }
    @SneakyThrows
    public static PooledConnection getConnection(String connName) throws SQLException {

        if (PoolManager.contains(connName)){
            return PoolManager.getConnection(connName);
        }
        ConnConfig connConfig = getConnConfig(connName);
        return createPool(connConfig);
    }

    @SneakyThrows
    public static void removeDataSourceById(String id) {
        Entity entity =  Db.use().get(Entity.create("conn").set("id", id));
        if (entity == null){
            return;
        }else {
            PoolManager.removeConnection(entity.getStr("connName"));
        }
    }
    @SneakyThrows
    public static void removeDataSource(String connName) {
        if (PoolManager.contains(connName)){
              PoolManager.removeConnection(connName);
        }
    }
}
